<template>
  <div id="data-screen-container" class="data-screen-container vab-data-fullscreen">
    <div class="header">
      <el-row style="height: 60px; line-height: 60px">
        <el-col :span="24">
          <div class="data-screen-header hidden-xs-only">
            <span>工陶院 BI 看板</span>
          </div>
          <div class="data-tabs">
            <span v-for="(item, i) in navList" :key="i" :class="i == navIndex ? 'active' : ''" @click="handleNav(i)">
              {{ item }}
            </span>
          </div>
          <div class="data-time">
            <span v-for="(item, i) in timeList" :key="i" :class="i == timeIndex ? 'active' : ''" @click="handleTime(i)">
              {{ item }}
            </span>

            <el-popover :visible="visible" placement="top" width="auto">
              <div style="margin-bottom: 16px">
                <el-date-picker
                  v-model="customTime"
                  type="datetimerange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  date-format="YYYY/MM/DD"
                  unlink-panels
                  @change="handleDateChange" />
              </div>
              <div style="text-align: center; margin: 0">
                <el-button size="small" text @click="handleCustomTime(false)">取消</el-button>
                <el-button size="small" type="primary" @click="handleCustomTime(true)"> 确定 </el-button>
              </div>
              <template #reference>
                <span
                  :class="timeIndex == 3 ? 'active' : ''"
                  @click="
                    visible = true;
                    timeIndex = 3;
                  "
                  >自定义</span
                >
              </template>
            </el-popover>
          </div>
        </el-col>
      </el-row>
    </div>
    <div style="padding: 30px 40px 0 40px" v-loading="loading">
      <!-- 采购看板 -->
      <PurchaseBi v-if="navIndex == 0" ref="purchaseBiRef" :type="timeIndex + 1" :timeRange="timeRange" />
      <!-- 仓库看板 -->
      <WarehouseBi v-if="navIndex == 1" ref="warehouseBiRef" :type="timeIndex + 1" :timeRange="timeRange" />
      <!-- 生产 -->
      <ProduceBi v-if="navIndex == 2" ref="produceBiRef" :type="timeIndex + 1" :timeRange="timeRange" />
      <!-- 设备看板 -->
      <DeviceBi v-if="navIndex == 3" ref="deviceBiRef" :type="timeIndex + 1" :timeRange="timeRange" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, ref, watch, watchEffect } from 'vue';
import DeviceBi from './device.vue';
import ProduceBi from './produce.vue';
import PurchaseBi from './purchase.vue';
import WarehouseBi from './warehouse.vue';
import dayjs from 'dayjs';

defineOptions({
  name: 'DataScreen',
});

import { ElMessage } from 'element-plus';

const navList = ['采购看板', '仓库看板', '生产看板', '设备看板'];
const navIndex = ref(0);
const timeList = ['本周', '本月', '本年'];
const timeIndex = ref(1); //时间下标
const timeRange = ref<any>(); //时间区间
const visible = ref(false);
const customTime = ref([]); //自定义时间

// 组件实例
const purchaseBiRef = ref<any>(null);
const warehouseBiRef = ref<any>(null);
const produceBiRef = ref<any>(null);
const deviceBiRef = ref<any>(null);
const loading = ref(false);

// 监听时间选择 刷新页面
watch(timeRange, (_newV, _oldV) => {
  if (!_oldV) return;
  loadComponent(true);
});

// watchEffect(() => {
//   const timer = setInterval(async() => {
//     loading.value = true;
//     await loadComponent();
//     setTimeout(() => {
//       loading.value = false;
//     }, 200);
//   }, 60 * 1000); // 60 * 1000毫秒即1分钟

//   return () => clearInterval(timer); // 组件销毁时清除定时器，避免内存泄漏
// });

onMounted(async() => {
  loading.value = true;
  timeRange.value = getTimePeriod(timeList[timeIndex.value]);
  await loadComponent();
  setTimeout(() => {
    loading.value = false;
  }, 200);
});


// 看板筛选 重置页面
const handleNav = (i: number) => {
  navIndex.value = i;
  loadComponent(false, true);
};
/**
 * 加载组件
 * @param isTimeSwitch 是否 时间切换
 * @param isNavSwitch  是否 标签切换
 */
const loadComponent = (isTimeSwitch = false, isNavSwitch = false) => {
  nextTick(() => {
    switch (navIndex.value) {
      case 0:
        if (purchaseBiRef.value) purchaseBiRef.value?.getPageData(isTimeSwitch);
        break;
      case 1:
        if (warehouseBiRef.value) warehouseBiRef.value.getPageData(isNavSwitch);
        break;
      case 2:
        if (produceBiRef.value) produceBiRef.value.getPageData(isNavSwitch);
        break;
      case 3:
        if (deviceBiRef.value) deviceBiRef.value.getPageData();
        break;
      default:
        break;
    }
  });
};

// 时间选择
const handleTime = async (i: number) => {
  visible.value = false;
  timeIndex.value = i;
  timeRange.value = await getTimePeriod(timeList[i]);
};

// 日期选择
const handleDateChange = async (val: any) => {
  if (val && val.length === 2) {
    const startDate = new Date(val[0]);
    const endDate = new Date(val[1]);
    const timeDiff = endDate.getTime() - startDate.getTime();
    const daysDiff = timeDiff / (1000 * 3600 * 24);
    if (daysDiff > 30) {
      ElMessage.warning('选择的日期范围不能超过 30 天');
      customTime.value = [];
    }
  }
};
// 自定义时间选择
const handleCustomTime = async (type: Boolean) => {
  visible.value = false;
  if (type) {
    timeRange.value = {
      startTime: dayjs(customTime.value[0]).format('YYYY-MM-DD'),
      endTime: dayjs(customTime.value[1]).format('YYYY-MM-DD'),
    };
  }
};

/**
 * Bi时间区间
 * @param period
 * @returns
 */
const getTimePeriod = (period: string) => {
  let now;
  if (import.meta.env.NODE_ENV === 'development') {
    // 开发环境，假设使用电脑时间（这里只是模拟，实际需获取电脑时间）
    now = new Date(2024, 10, 21);
  } else {
    // 生产环境，使用系统时间
    now = new Date();
  }
  let startDate, endDate;

  switch (period) {
    case '本周':
      const currentDay = now.getDay();
      startDate = new Date(now.getTime() - currentDay * 24 * 60 * 60 * 1000);
      startDate.setDate(startDate.getDate() + 1); // 确保是周一
      startDate.setHours(0, 0, 0, 0);
      endDate = new Date(startDate.getTime() + 6 * 24 * 60 * 60 * 1000);
      endDate.setHours(23, 59, 59, 999);
      break;
    case '本月':
      startDate = new Date(now.getFullYear(), now.getMonth(), 1);
      startDate.setHours(0, 0, 0, 0);
      const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
      endDate = new Date(nextMonth.getTime() - 1);
      endDate.setHours(23, 59, 59, 999);
      break;
    case '本年':
      startDate = new Date(now.getFullYear(), 0, 1);
      startDate.setHours(0, 0, 0, 0);
      endDate = new Date(now.getFullYear(), 11, 31, 23, 59, 59, 999);
      break;
    default:
      return null;
  }

  return {
    startTime: `${startDate.getFullYear()}-${String(startDate.getMonth() + 1).padStart(2, '0')}-${String(
      startDate.getDate()
    ).padStart(2, '0')}`,
    endTime: `${endDate.getFullYear()}-${String(endDate.getMonth() + 1).padStart(2, '0')}-${String(
      endDate.getDate()
    ).padStart(2, '0')}`,
  };
};
</script>

<style lang="scss" scoped>
#data-screen-container.data-screen-container.vab-data-fullscreen {
  overflow: auto;
  color: #fff;
  background: #000d19 !important;

  :deep(){
    .el-loading-mask{
      background-color: rgba(0, 13, 25, 0.8);
    }
  }

  .header {
    overflow: hidden;
    position: sticky;
    top: 0;
    z-index: 10;
  }

  .data-screen-card {
    position: relative;
    width: 100%;
    min-height: 160px;
    padding: var(--el-padding);
    margin-bottom: 20px;
    border: 3px solid #01ffff;
    border-radius: 5px;

    .card-title {
      height: 20px;
      padding-left: 10px;
      line-height: 20px;
      text-align: left;
      border-left: 3px solid #01ffff;
    }

    &::before {
      position: absolute;
      top: -3px;
      bottom: -3px;
      left: 30px;
      z-index: 0;
      width: calc(100% - 60px);
      pointer-events: none;
      content: '';
      border-top: 3px solid #101f58;
      border-bottom: 3px solid #101f58;
    }

    &::after {
      position: absolute;
      top: 30px;
      right: -3px;
      left: -3px;
      z-index: 0;
      height: calc(100% - 60px);
      pointer-events: none;
      content: '';
      border-right: 3px solid #101f58;
      border-left: 3px solid #101f58;
    }
  }
}

@keyframes flare {
  0% {
    background-position: -400px;
  }

  30% {
    background-position: 0;
  }

  100% {
    background-position: 400px;
    opacity: 0;
  }
}

.data-screen-header {
  width: 100%;
  margin-bottom: 20px;
  text-align: center;
  background: url('/@/assets/images/bgtop2.png') no-repeat;
  background-size: 100% 100%;

  .data-go-home,
  .data-fullscreen {
    position: fixed;
    top: 13px;
    z-index: 999;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60px;
    height: 60px;
    background: #395dfe;
    border-radius: 50%;
    box-shadow: 0 2px 12px 0 #395dfe;

    :deep() {
      [class*='ri-'] {
        font-size: var(--el-font-size-extra-large);
        color: #fff;
      }
    }
  }

  .data-go-home {
    left: 40px;
  }

  .data-fullscreen {
    right: 40px;
  }

  span {
    position: relative;
    font-size: 30px;
    font-weight: bold;
    color: #33e6fa;
    background: linear-gradient(-90deg, #7cedfb 0%, #2ba3ff 0%, #02efff 50.2685546875%, #2ea5f9 100%);
    background-clip: text;
    -webkit-text-fill-color: transparent;

    &::before {
      position: absolute;
      left: 0;
      top: -12px;
      display: block;
      width: 100%;
      color: #fff;
      content: '工陶院 BI 看板';
      background-image: linear-gradient(
        65deg,
        transparent 10%,
        rgba(255, 255, 255, 1) 20%,
        rgba(255, 255, 255, 1) 27.5%,
        transparent 30%,
        transparent 100%
      );
      background-clip: text;
      animation: flare 3s infinite;
    }

    &::after {
      position: absolute;
      top: 0;
      z-index: -1;
      display: block;
      color: #fff;
      content: '工陶院 BI 看板';
    }
  }

  &.mobile-only {
    .data-fullscreen,
    .data-go-home {
      width: 40px;
      height: 40px;
    }

    .mobile-title {
      position: relative;
      font-size: var(--el-font-size-extra-large);
      font-weight: bold;
      color: #33e6fa;
      background: linear-gradient(-90deg, #7cedfb 0%, #2ba3ff 0%, #02efff 50.2685546875%, #2ea5f9 100%);
      background-clip: text;
      -webkit-text-fill-color: transparent;

      &::before {
        position: absolute;
        left: 0;
        display: block;
        width: 100%;
        color: #fff;
        content: '数据大屏';
        background-image: linear-gradient(
          65deg,
          transparent 10%,
          rgba(255, 255, 255, 1) 20%,
          rgba(255, 255, 255, 1) 27.5%,
          transparent 30%,
          transparent 100%
        );
        background-clip: text;
        animation: flare 3s infinite;
      }

      &::after {
        position: absolute;
        top: 0;
        z-index: -1;
        display: block;
        color: #fff;
        content: '数据大屏';
      }
    }
  }
}

.data-tabs {
  position: absolute;
  left: 70px;
  top: 18px;
  width: 20%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  white-space: nowrap;
  /* 确保文本在一行内显示 */
  overflow: hidden;
  /* 隐藏溢出的内容 */
  text-overflow: ellipsis;
  /* 使用省略号表示文本溢出 */

  span {
    font-family: 'PingFangSC-Regular', 'PingFang SC';
    font-weight: 400;
    font-style: normal;
    font-size: 16px;
    color: rgba(42, 174, 245, 0.4);
    cursor: pointer;

    &.active {
      font-weight: 650;
      font-style: normal;
      font-size: 20px;
      color: #2aaef5;
      animation: fadeIn 1s both;
    }
  }
}

.data-time {
  width: 26%;
  display: flex;
  align-items: center;
  position: absolute;
  right: 0px;
  top: 18px;
  font-weight: 650;
  font-style: normal;
  font-size: 20px;
  color: #2aaef5;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;

  span {
    font-family: 'PingFangSC-Regular', 'PingFang SC';
    font-weight: 400;
    font-style: normal;
    font-size: 16px;
    color: rgba(42, 174, 245, 0.4);
    cursor: pointer;
    margin-right: 20px;

    &:last-child {
      margin-right: 0px;
    }

    &.active {
      font-weight: 650;
      font-style: normal;
      font-size: 20px;
      color: #2aaef5;
      animation: fadeIn 1s both;
    }
  }
}
</style>
